package com.springboot.oauth2.config.custom;

import com.alibaba.fastjson.JSON;
import org.springframework.security.jwt.JwtHelper;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.token.store.JwtAccessTokenConverter;

import java.util.HashMap;

/**
 * 显式增加oauth/token返回的信息，token之外能看到新增的字段，token内也能看到
 *
 * @author han
 */
public class MyJwtAccessTokenConverter extends JwtAccessTokenConverter {

  @Override
  public OAuth2AccessToken enhance(
      OAuth2AccessToken accessToken, OAuth2Authentication authentication) {
    if (accessToken instanceof DefaultOAuth2AccessToken) {
      // 获取token请求
      Object principal = authentication.getPrincipal();
      HashMap<String, Object> map = new HashMap<>();
      if (principal instanceof User) {
        User user = (User) principal;
        map.put("user_id", user.getUserId());
        map.put("phone", user.getPhone());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
      }
      if (principal instanceof String) {
        // 刷新token请求
        String refreshToken = accessToken.getRefreshToken().getValue();
        String claims = JwtHelper.decode(refreshToken).getClaims();
        HashMap hashMap = JSON.parseObject(claims, map.getClass());
        map.put("user_id", hashMap.get("user_id").toString());
        map.put("phone", hashMap.get("phone").toString());
        ((DefaultOAuth2AccessToken) accessToken).setAdditionalInformation(map);
      }
    }
    return super.enhance(accessToken, authentication);
  }
}
